import { contentToHighlight } from '@/utils/editorEvent';
import { message } from 'antd';
import React, { useMemo, useState } from 'react';
import { ResponseType } from '@/types/index';
import { ReplyContext } from './context';
import styles from './index.less';
import ReplyItem from './ReplyItem';
import Submit from './Submit';
import TotalWord from './TotalWord';

const ReplyInput: React.FC<Reply.ParamsProps> = (props) => {
  const {
    minWordCount = 0,
    maxWordCount,
    inputList = [],
    onSubmit,
    onCancel,
    onReplyError,
    defaultValue,
  } = props;
  const [totalWordCount, setTotalWordCount] = useState<number>(0);
  const [reply, setReply] = useState<{}>({});
  const [updateInputValue, setUpdateInputValue] = useState<{}>({});

  const isReplyError = (res: ResponseType) => {
    const { code, info } = res;
    if (onReplyError) {
      return onReplyError(res);
    }

    if (code) {
      message.info(info);
      return true;
    }

    message.success('回复成功');
    return false;
  };

  const errorInput = (data: {}) => {
    const obj = {};
    inputList.forEach((item, index) => {
      obj[index] = contentToHighlight(data[`replyError_${index}`]);
    });
    setUpdateInputValue({ ...obj });
  };

  const clearInput = () => {
    const obj = {};
    inputList.forEach((item, index) => {
      obj[index] = '';
    });
    setUpdateInputValue({ ...obj });
    setReply({});
  };

  const checkInputEmpty = (replyList: []) => {
    let state = false;

    inputList.forEach((item, index) => {
      if (!replyList[index]) {
        state = true;
      }
    });

    return state;
  };

  const handleSubmitForm = async () => {
    const replyList: number[] = Object.values(reply);

    if (checkInputEmpty(replyList)) {
      message.info('请确保每个输入框不为空');
      return;
    }

    await onSubmit(replyList).then((res: ResponseType = {}) => {
      // console.log('handleError(res)',handleError(res));
      // return
      const { code, data, info } = res;
      if (code === 1001) {
        errorInput(data);
        message.error(info);
        return;
      }
      if (isReplyError(res)) return;
      clearInput();
      setTotalWordCount(0);
    });
  };

  const totalWordNumber = () => {
    let total = 0;
    Object.values(reply).forEach((item) => {
      const str = item.match(/[\u4e00-\u9fa5]/g);
      total += str ? str.length : 0;
    });
    setTotalWordCount(total);
  };

  useMemo(() => {
    totalWordNumber();
  }, [reply]);

  useMemo(() => {
    if (inputList.length) {
      setTotalWordCount(0);
    }
  }, [inputList]);

  useMemo(() => {
    if (defaultValue) {
      const obj = {};
      defaultValue.forEach((item, index) => {
        obj[index] = item;
      });
      setUpdateInputValue({ ...obj });
      setReply({ ...obj });
    }
  }, [defaultValue]);

  return (
    <ReplyContext.Provider value={{ inputList, totalWordCount, reply, setReply, updateInputValue }}>
      <div>
        <div className={styles['reply-title']}>我的回复</div>
        {inputList &&
          inputList.length &&
          inputList.map((item, index) => {
            return <ReplyItem key={index} type={index} placeholder={item} />;
          })}
        <div className={styles['btn-box']}>
          <TotalWord minWordCount={minWordCount} />
          <Submit
            minWordCount={minWordCount}
            maxWordCount={maxWordCount}
            onSubmit={handleSubmitForm}
            onCancel={onCancel}
          />
        </div>
      </div>
    </ReplyContext.Provider>
  );
};

export default ReplyInput;
